import 'package:flutter/material.dart';

import '../chat_box.dart';
import '../viewmodel/general_viewmodel.dart';

class MyAnimatedList extends StatefulWidget {
  final RespondsScrollViewmodel listNotifier;
  final Widget Function(BuildContext context, ResponseModel item, Animation<double> animation) itemBuilder;
  final ScrollController controller;
  final ScrollPhysics physics;

  const MyAnimatedList({
    super.key,
    required this.listNotifier,
    required this.itemBuilder,
    required this.controller,
    required this.physics,
  });

  @override
  State<MyAnimatedList> createState() => _MyAnimatedListState();
}

class _MyAnimatedListState extends State<MyAnimatedList> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
  List<ResponseModel> _oldItems = [];

  @override
  void initState() {
    super.initState();

    // 初始值
    _oldItems = List.from(widget.listNotifier.responds);

    // 监听 ValueNotifier
    widget.listNotifier.addListener(_onListChanged);
  }

  @override
  void dispose() {
    widget.listNotifier.removeListener(_onListChanged);
    super.dispose();
  }

  void _onListChanged() {
    final newList = widget.listNotifier.responds;
    final diffCount = newList.length - _oldItems.length;

    if (diffCount > 0) {
      for (int i = 0; i < diffCount; i++) {
        _listKey.currentState?.insertItem(0, duration: const Duration(milliseconds: 100));
      }
    }
    else if (diffCount < 0) {
      for (int i = 0; i < diffCount.abs(); i++) {
        var removedItem = _oldItems.removeAt(0);
        _listKey.currentState?.removeItem(0, (context, animation){
          return SizeTransition(
            sizeFactor: animation,
            axis: Axis.vertical,
            child: Padding(
              padding: const EdgeInsets.fromLTRB(10, 5, 16, 5),
              child: ResponseView(
                model: removedItem,
              ),
            ),
          );
        },
        duration: const Duration(milliseconds: 100));
      }
    }

    _oldItems = List.from(newList);

  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        AnimatedList(
          key: _listKey,
          controller: widget.controller,
          physics: widget.physics,
          initialItemCount: _oldItems.length,
          itemBuilder: (context, index, animation) {
            final item = widget.listNotifier.responds[index];

            return widget.itemBuilder(context, item, animation);
          },
        ),

        ListenableBuilder(
          listenable: widget.listNotifier,
          builder: (context, _) {
            if (widget.listNotifier.responds.isEmpty) {
              return const Center(
                child: Text("The responses will be\ndisplayed here.", style: TextStyle(color: Colors.white), textAlign: TextAlign.center,),
              );
            }
            return const SizedBox.shrink();
          }
        )
      ],
    );
  }
}